package com.bootdo.common.task;

import com.bootdo.app.service.LevelProfitService;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.bootdo.app.dto.wx.TemplateMsgRequest;
import com.bootdo.app.service.WXService;
import com.bootdo.app.service.impl.UserCashOutServiceImpl;
import com.bootdo.common.utils.DateUtils;
import com.bootdo.common.utils.HttpUtil;
import com.bootdo.system.config.KswApi;
import com.bootdo.system.domain.TbJcLog;
import com.bootdo.system.domain.TbMtlm;
import com.bootdo.system.domain.TbOrder;
import com.bootdo.system.domain.TbUserWater;
import com.bootdo.system.domain.TbWeixinconfig;
import com.bootdo.system.domain.TbWxmenu;
import com.bootdo.system.domain.TbWxuser;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.MtlmService;
import com.bootdo.system.service.OrderService;
import com.bootdo.system.service.UserLsService;
import com.bootdo.system.service.UserService;
import com.bootdo.system.service.WxConfigService;
import com.bootdo.system.service.WxMenuService;
import com.bootdo.system.service.WxUserService;

import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
@Slf4j
@Component
public class WelcomeJob implements Job{
	@Autowired
	SimpMessagingTemplate template;
	
	@Autowired
	MtlmService mtlmService;
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private WXService wXService;
	
	@Autowired
	private WxUserService wxUserService;
	
	@Autowired
	private WxConfigService wxConfigService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private UserLsService userLsService;
	
	@Autowired
	private WxMenuService wxMenuService;

	@Autowired
	private LevelProfitService levelProfitService;
	

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
//    	template.convertAndSend("/topic/getResponse", new Response("" ));
    	 log.info("定时器开始执行");
    	List<TbMtlm> list = mtlmService.getList("1");
    	if(list != null && list.size() > 0) {
    		for (TbMtlm tbMtlm : list) {
    			//去美团联盟查询订单状态
    			String sid2 = tbMtlm.getSid();
    			if(!StringUtils.isNoneBlank(sid2)) {
    				tbMtlm.setStatus("2");
    				mtlmService.insert2update(tbMtlm);
    				continue;
    			}
    			String[] split = sid2.split("@");
    			if(split.length != 2) {
    				tbMtlm.setStatus("2");
    				mtlmService.insert2update(tbMtlm);
    				continue;
    			}
    			log.info("开始处理订单:"+tbMtlm.toString());
    			Integer ordStatus=0;
    			boolean falg=true;
    			TbWeixinconfig selectByUserId = wxConfigService.selectByUserId(Integer.valueOf(split[0]));
    			if(selectByUserId != null) {
    				if(StringUtils.isNoneBlank(selectByUserId.getProxykey()) && StringUtils.isNoneBlank(selectByUserId.getProxysecret())) {
    					Integer sfzy = selectByUserId.getSfzy();
    					if(sfzy == 1) {
    						falg=false;
    					}
    					ordStatus = getOrdStatus(selectByUserId.getProxykey(),selectByUserId.getProxysecret(),tbMtlm.getOrderid());
    				}else{
//   					 	ordStatus = getOrdStatus(KswApi.MTLM_KEY,KswApi.MTLM_SECRET,tbMtlm.getOrderid());
    					continue;
    				}
    			}
    			if(ordStatus == 8) {
    				int update = update(tbMtlm,falg);
        			if(update > 0) {
        				//设置状态为
        				tbMtlm.setStatus("8");
        				mtlmService.insert2update(tbMtlm);
        			}
    			}else if(ordStatus == 9) {
    				int update = update2(tbMtlm);
        			if(update > 0) {
        				//设置状态为
        				tbMtlm.setStatus("9");
        				mtlmService.insert2update(tbMtlm);
        			}
    			}
			}
    	}

    }
    
    
    private Integer getOrdStatus(String key,String secret,String oid) {
		TreeMap<String, String> treeMap = new TreeMap<String, String>();
	    treeMap.put("key" , key);
	    treeMap.put("oid" , oid);
	    treeMap.put("full" , "1");
	    treeMap.put("type" , "4");
	    treeMap.put("sign" , genSign(treeMap,secret));
	    String s = HttpUtil.doGet(KswApi.MTLM_ORDER,treeMap);
	    System.out.println(s);
	    if(StringUtils.isNoneBlank(s)) {
	    	  HashMap<String,Map<String,Object>> hashMap = JSON.parseObject(s, HashMap.class);
	  	    Map<String, Object> map = hashMap.get("order");
	  	    Integer status = (Integer) map.get("status");
	  	    return status;
	    }
	   return 0;
	  
    }
    
    public  String genSign(TreeMap<String, String> params,String secret) {
		if (params.containsKey("sign")) {
		    params.remove("sign");
		}
		String str = "";
		str += secret;
		for (String key : params.keySet()) {
		    str += key + params.get(key);
		}
		str += secret;
		String sign = md5(str);
		return sign;
	}
	public  String md5(String source) {
		String md5Result = null;
		try {
		        byte[] hash = org.apache.commons.codec.binary.StringUtils.getBytesUtf8(source);
		        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
		        messageDigest.update(hash);
		        hash = messageDigest.digest();
		        md5Result = Hex.encodeHexString(hash);
		} catch (NoSuchAlgorithmException e) {
		        e.printStackTrace();
		}
		return md5Result;
	}
    
    
    public int update(TbMtlm table,boolean falg) {
		//sid 拼接必须要   商家id+@+openId
		System.out.println(table.toString());
		
		String sid2 = table.getSid();
		if(!StringUtils.isNoneBlank(sid2)) {
			return -1;
		}
		String[] split = sid2.split("@");
		if(split.length != 2) {
			return -1;
		}
		
//		
		TbOrder double2Order = orderService.getByIdOid(table.getOrderid(),split[1]);
		
		if(double2Order == null) {
			return -1;
		}
		
//		List<TbOrder> byIdOid2 = orderService.getByIdOid2(table.getOrderid());
//		for (TbOrder tbOrder : byIdOid2) {
//			tbOrder.setStatus(2);
//			orderService.insert2update(tbOrder);
//		}		
//		double2Order.setStatus(2);
			
			//2佣金处理
			//佣金总金额
			Double profit = getDouble2String(table.getDirect());
			String ratio = table.getRatio();
			Double double2ratio = getDouble2String(ratio);
			profit=profit * double2ratio;
			TbWxuser userById = wxUserService.getUserById(split[1]);
			if(userById == null) {
				return -1;
			}
			
			//根据后台用户id 查询佣金比例
			String sid = userById.getSid();
			TbWeixinconfig selectByUserId = wxConfigService.selectByUserId(Integer.valueOf(sid));
			TbWxmenu selectByUserId2 = wxMenuService.selectByUserId(Integer.valueOf(sid));

			if(falg) {
				// 余额放入 后台用户余额
				UserDO userDO = userService.get(Long.valueOf(sid));
				String balanceuc = userDO.getBalance();
				Double balanceu = getDouble2String(balanceuc);
				userDO.setBalance((balanceu+profit)+"");
				userService.update4(userDO);
			}
			
			//记录用户流水
			TbUserWater tbUserWater = new TbUserWater();
			//用户下单类型
			tbUserWater.setZjlx(4);
			tbUserWater.setWaterJe(profit+"");
			tbUserWater.setUserId(Long.valueOf(sid));
			tbUserWater.setOrderId(table.getOrderid());
			tbUserWater.setOrderType(1);
			userLsService.insert(tbUserWater);

            Map map = levelProfitService.selecLevelProfitMap(userById.getUserType());
            if(map == null){
                map = new HashMap();
            }
            Double one_profit = (Double) map.get("one_profit") == 0.00 ? 100:(Double) map.get("one_profit");
            Double double2String = getDouble2String(double2Order.getProfit())*(one_profit/100);
			Double balance = getDouble2String(userById.getBalance());
			userById.setBalance((balance+(double2String))+"");
			wxUserService.insert2update(userById);
			
			//记录用户奖励
			TbJcLog tbJcLog = new TbJcLog();
			tbJcLog.setWxId(userById.getId());
			tbJcLog.setJcje(new BigDecimal(double2String));
			tbJcLog.setUserId(Integer.valueOf(sid));
			tbJcLog.setJczt(1);
			tbJcLog.setJcbz("美团返佣");
			wxUserService.insertJc(tbJcLog);
			
			double2Order.setStatus(2);
			orderService.insert2update(double2Order);
			
			//发送模板消息 String toUserOpenId,String url,String orderName,String orderTime,String orderMoney,String commission
			if(userById.getGzhOpenId() != null) {
				TemplateMsgRequest newUserJoin = TemplateMsgRequest.createOrderConfirm(userById.getGzhOpenId(),null, table.getSmstitle(), table.getOrderid(), table.getSmstitle(),double2Order.getPaytime(),double2Order.getPaytime(), DateUtils.format(new Date()),(double2String)+"",selectByUserId.getServiceTemplate2());
	            wXService.sendTemplateMsg(selectByUserId2.getAppid(), selectByUserId2.getAppsecret(), newUserJoin);
	            
	            TemplateMsgRequest newUserJoin2 = TemplateMsgRequest.createBalanceChange(userById.getGzhOpenId(),null, DateUtils.format(new Date()), "用户佣金",(double2String)+"",(balance+(double2String))+"",selectByUserId.getServiceTemplate3());
	            wXService.sendTemplateMsg(selectByUserId2.getAppid(), selectByUserId2.getAppsecret(), newUserJoin2);
			
			}
			
			//处理上一级佣金
			Integer wxuserId = userById.getWxuserId();
			TbWxuser userById2 = wxUserService.getById(wxuserId);
			if(userById2 != null) {
				TbOrder double2Order2 = orderService.getByIdOid(table.getOrderid(),userById2.getOpenidXcx());
				if(double2Order2 != null) {
                    Map map1 = levelProfitService.selecLevelProfitMap(userById2.getUserType());
                    if(map1 == null){
                        map1 = new HashMap();
                    }
                    Double two_profit = (Double) map1.get("two_profit") == null ? 100:(Double) map1.get("one_profit");;
                    Double double2String2 = getDouble2String(double2Order2.getProfit())*(two_profit/100);
					
					Double balance2 = getDouble2String(userById2.getBalance());
					userById2.setBalance((balance2+(double2String2))+"");
					wxUserService.insert2update(userById2);
					
					//记录用户奖励
					TbJcLog tbJcLog2 = new TbJcLog();
					tbJcLog2.setWxId(userById2.getId());
					tbJcLog2.setJcje(new BigDecimal(double2String2));
					tbJcLog2.setUserId(Integer.valueOf(sid));
					tbJcLog2.setJczt(1);
					tbJcLog2.setJcbz(userById.getNickname()+"好友返佣");
					wxUserService.insertJc(tbJcLog2);
					
					
					double2Order2.setStatus(2);
					orderService.insert2update(double2Order2);
					
					//发送模板消息
					
					if(userById2.getGzhOpenId() != null) {
						//String toUserOpenId,String url,String orderName,String orderNum,String goodsName,String orderTime,String shippingTime,String confirmOrderTime,String commission
						TemplateMsgRequest newUserJoin = TemplateMsgRequest.createOrderConfirm(userById2.getGzhOpenId(),null, table.getSmstitle(), table.getOrderid(), table.getSmstitle(),double2Order.getPaytime(),double2Order.getPaytime(), DateUtils.format(new Date()),(double2String2)+"",selectByUserId.getServiceTemplate2());
			            wXService.sendTemplateMsg(selectByUserId2.getAppid(), selectByUserId2.getAppsecret(), newUserJoin);
			            
			            TemplateMsgRequest newUserJoin2 = TemplateMsgRequest.createBalanceChange(userById2.getGzhOpenId(),null, DateUtils.format(new Date()), "用户佣金",(balance2)+"",(balance2+(double2String2))+"",selectByUserId.getServiceTemplate3());
			            wXService.sendTemplateMsg(selectByUserId2.getAppid(), selectByUserId2.getAppsecret(), newUserJoin2);
					
					}
					
					//处理上二级佣金
					Integer wxuserId2 = userById2.getWxuserId();
					TbWxuser userById3 = wxUserService.getById(wxuserId2);
					if(userById3 != null) {
						TbOrder double2Order3 = orderService.getByIdOid(table.getOrderid(),userById3.getOpenidXcx());
						if(double2Order3 != null) {
                            Map map2 = levelProfitService.selecLevelProfitMap(userById3.getUserType());
                            if(map2 == null){
                                map2 = new HashMap();
                            }
                            Double three_profit = (Double) map2.get("three_profit") == null? 100:(Double) map1.get("one_profit");;;
                            Double double2String3 = getDouble2String(double2Order3.getProfit())*(three_profit/100);
							
							Double balance3 = getDouble2String(userById3.getBalance());
							userById3.setBalance((balance3+(double2String3))+"");
							wxUserService.insert2update(userById3);
							
							//记录用户奖励
							TbJcLog tbJcLog3 = new TbJcLog();
							tbJcLog3.setWxId(userById3.getId());
							tbJcLog3.setJcje(new BigDecimal(double2String3));
							tbJcLog3.setUserId(Integer.valueOf(sid));
							tbJcLog3.setJczt(1);
							tbJcLog3.setJcbz(userById2.getNickname()+"好友返佣");
							wxUserService.insertJc(tbJcLog3);
							
							double2Order3.setStatus(2);
							orderService.insert2update(double2Order3);
							
							//发送模板消息
							if(userById3.getGzhOpenId() != null) {
								TemplateMsgRequest newUserJoin = TemplateMsgRequest.createOrderConfirm(userById3.getGzhOpenId(),null, table.getSmstitle(), table.getOrderid(), table.getSmstitle(),double2Order.getPaytime(),double2Order.getPaytime(), DateUtils.format(new Date()),(double2String3)+"",selectByUserId.getServiceTemplate2());
					            wXService.sendTemplateMsg(selectByUserId2.getAppid(), selectByUserId2.getAppsecret(), newUserJoin);
					            
					            TemplateMsgRequest newUserJoin2 = TemplateMsgRequest.createBalanceChange(userById3.getGzhOpenId(),null, DateUtils.format(new Date()), "用户佣金",(balance3)+"",(balance3+(double2String3))+"",selectByUserId.getServiceTemplate3());
					            wXService.sendTemplateMsg(selectByUserId2.getAppid(), selectByUserId2.getAppsecret(), newUserJoin2);
							
							}
						}
					}
					
				}
			}
				
				
			
			return 1;
	}
	private Double getDouble2String(String num) {
		if(StringUtils.isNoneBlank(num)) {
			Double cny = Double.parseDouble(num);
			DecimalFormat df = new DecimalFormat("0.00000"); 
			String CNY = df.format(cny);
			Double cny1 = Double.parseDouble(CNY);
			return cny1;
		}
		return 0.00;
	}
	
	private TbOrder getDouble2Order(TbMtlm table) {
		TbOrder tbOrder = new TbOrder();
		tbOrder.setTitle(table.getSmstitle());
		tbOrder.setOid(table.getOrderid());
		tbOrder.setTotal(table.getTotal());
		tbOrder.setDirect(table.getDirect());
		tbOrder.setPaytime(table.getPaytime());
		tbOrder.setSid(table.getSid());
		//媒体方id
		tbOrder.setSidName(table.getUid());
		String sid = table.getSid();
		String[] split = sid.split("@");
		tbOrder.setOpenid(split[1]);
		
		//返佣是根据总金额还是实际支付金额
		//目前使用实际支付金额
		Double ratio = getDouble2String(table.getRatio());
		Double direct = getDouble2String(table.getDirect());
		if(ratio == 0 || direct == 0) {
			tbOrder.setProfit("0");
		}else {
			Double res=ratio*direct;
			tbOrder.setProfit(res.toString());
		}
		//订单签名不知用意？
		return tbOrder;
	}
	
	
	public int update2(TbMtlm table) {
		int res=0;
		List<TbOrder> byIdOid2 = orderService.getByIdOid2(table.getOrderid());
		for (TbOrder tbOrder : byIdOid2) {
			tbOrder.setStatus(4);
			res=orderService.insert2update(tbOrder);
		}
		return res;
	}

}